﻿/****************************************************
	文件：UserMgr.cs
	作者：HuskyT
	邮箱:  1005240602@qq.com
	日期：2020/05/02 11:32   	
	功能：用户 管理类
*****************************************************/

using HTServer.Proto;
using MySql;
using MySql.Data;
using System;

namespace HTServer.Business
{
    public class UserMgr : Singleton<UserMgr>
    {
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param 注册类型="registerType"></param>
        /// <param 用户名="userName"></param>
        /// <param 密码="pwd"></param>
        /// <returns></returns>
        public RegisterResult Register(RegisterType registerType, string userName, string pwd, out string token)
        {
            token = "";
            try
            {
                int count = MySqlMgr.Instance.Db.Queryable<User>().Where(it => it.Username == userName).Count();
                if (count > 0) return RegisterResult.AlreadyExist;//用户名已存在
                User user = new User();
                switch (registerType)
                {
                    //使用手机/邮箱进行注册的时候，会在执行 Register（当前方法）之前通过一个网络协议申请验证码
                    //将验证码存储到Db，并保存验证码时间，用于验证有效期
                    //在执行当前 Register 方法时会从Db中取出验证码和验证码时间，来检验验证码是否一致、且在有效期内
                    case RegisterType.Phong:
                        user.Logintype = LoginType.Phong.ToString();
                        break;
                    case RegisterType.Email:
                        user.Logintype = LoginType.Email.ToString();
                        break;
                    default:
                        break;
                }
                user.Logintime = DateTime.Now;
                user.Username = userName;
                user.Password = pwd;
                user.Token = Guid.NewGuid().ToString();
                MySqlMgr.Instance.Db.Insertable(user).ExecuteCommand();//插入数据
                token = user.Token;
                return RegisterResult.Success;
            }
            catch (Exception e)
            {
                Debug.LogError("用户注册失败，Exception：" + e.ToString());
                return RegisterResult.Failure;
            }
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param 登录类型="loginType"></param>
        /// <param 用户名="userName"></param>
        /// <param 密码="pwd"></param>
        /// <param 用户唯一标识="userId"></param>
        /// <param 自动登录使用的="token"></param>
        /// <returns></returns>
        public LoginResult Login(LoginType loginType, string userName, string pwd, out int userId, out string token)
        {
            userId = 0;
            token = "";
            try
            {
                User user = null;
                switch (loginType)
                {
                    case LoginType.Phong:
                    case LoginType.Email:
                        user = MySqlMgr.Instance.Db.Queryable<User>().Where(it => it.Username == userName).Single();
                        break;
                    //使用微信、QQ登录，会保存一个Unionid，查询的时候是：it.Unionid == userName
                    case LoginType.WX:
                    case LoginType.QQ:
                        break;
                    case LoginType.Token:
                        user = MySqlMgr.Instance.Db.Queryable<User>().Where(it => it.Username == userName).Single();
                        break;
                    default:
                        break;
                }
                if (user == null)//在Db中找不到对应的User信息
                {
                    if (loginType == LoginType.QQ || loginType == LoginType.WX)//QQ/微信 登录
                    {
                        //首次登录，直接自动注册
                        //在数据库注册
                        user = new User();
                        user.Username = userName;
                        user.Password = pwd;
                        user.Token = Guid.NewGuid().ToString();
                        user.Logintype = loginType.ToString();
                        user.Logintime = DateTime.Now;
                        userId = MySqlMgr.Instance.Db.Insertable(user).ExecuteReturnIdentity();
                        //存储Unionid = userId
                        token = user.Token;
                        return LoginResult.Success;
                    }
                    else
                        return LoginResult.UserNoExist;
                }
                else //在Db中找到了对应的User信息
                {
                    if (loginType != LoginType.Token)//不是自动登录
                    {
                        if (loginType == LoginType.Phong || loginType == LoginType.Email)//手机/邮箱 登录
                        {
                            if (user.Password != pwd)
                                return LoginResult.WrongPwd;
                        }
                    }
                    else//Token 自动登录
                    {
                        if (user.Token != pwd)
                            return LoginResult.TimeoutToken;
                    }
                    user.Token = Guid.NewGuid().ToString();
                    user.Logintime = DateTime.Now;
                    MySqlMgr.Instance.Db.Updateable(user).ExecuteCommand();//更新到Db
                    userId = user.Id;
                    token = user.Token;
                    return LoginResult.Success;
                }
            }
            catch (Exception e)
            {
                Debug.LogError("登录失败，Exception：" + e.ToString());
                return LoginResult.Failure;
            }
        }
    }
}